import { storeToRefs } from 'pinia'
import { useUserStore } from '../store/index'
import { RouteRecordRaw} from 'vue-router'
import router from '../router/index'

const forMatUrl = (name: string) => {

    if(name.includes("records/")){
        return "Records";
    }
    return name.substring(0, 1).toUpperCase() + name.substring(1)
}
const asyncRouter = () => {
    const userStore = useUserStore();
    const { menus} = storeToRefs(userStore);
    const homeRoute: RouteRecordRaw =
    {
        path: "/",
        name: "Home",
        component: () => import("../views/Home.vue"),
        children: []
    }
   
    menus.value.forEach((item: any) => {

        item.children.forEach((subItem: any) => {


            let route = {
                path: subItem.url.includes("records/") ? "records/:typeid" : subItem.url,
                name: subItem.url,
                component: () => import("../views/" + forMatUrl(subItem.url) + ".vue")
            }

            homeRoute.children.push(route);


        })


    });

    return homeRoute;
}

 

router.beforeEach((to:any) => {
 
    const userStore = useUserStore();
    const { token } = storeToRefs(userStore);
    if(to.path=="/login"){

         return true;
    }
    if(!token.value){
        return "/login";
    }
    if(router.getRoutes().length<2){
        
        const routers=asyncRouter();
        router.addRoute(routers);
        return to.fullPath;

    }

})